//Clean up
//Streamlime make OOP
//See why urls not being printed at end
//Add gui
//-depth to crawl
//-start url
//crawl only TLD
//crawl only HTML pages

var mainWindow = null;
mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                     .getInterface(Components.interfaces.nsIWebNavigation)
                     .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
                     .rootTreeItem
                     .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                     .getInterface(Components.interfaces.nsIDOMWindow);
							 
var urlhash = new Array();
var urlq = new Array();				
var visited=0;	
var start=0; 
var max_visited;
					 
const STATE_START = Components.interfaces.nsIWebProgressListener.STATE_START;
const STATE_STOP = Components.interfaces.nsIWebProgressListener.STATE_STOP;

var myListener =
{
  QueryInterface: function(aIID)
  {
   if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
       aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
       aIID.equals(Components.interfaces.nsISupports))
     return this;
   throw Components.results.NS_NOINTERFACE;
  },
  
 onStateChange: function(aWebProgress, aRequest, aFlag, aStatus)
  {
   // If you use myListener for more than one tab/window, use
   // aWebProgress.DOMWindow to obtain the tab/window which triggers the state change
   if(aFlag & STATE_START)
   {
     // This fires when the load event is initiated
   }
   if(aFlag & STATE_STOP)
   {
     // This fires when the load finishes
	 getLinks();
	 
	 	//var ele1 = mainWindow.content.document.getElementById("searchform");
	//var ele2 = mainWindow.DOM.getXPathForElement_id_class(ele1);
	//alert('test '+ele1 + ' ');
	
	 if(start) startCrawl();
	 
	//for(var i=0;i<10000000;i++){}
	 //getLinks1();
   }
  },
  

  onLocationChange: function(aProgress, aRequest, aURI)
  {
	getURL();
    getLinks();
	if(start) addUrl();

	
   // This fires when the location bar changes; that is load event is confirmed
   // or when the user switches tabs. If you use myListener for more than one tab/window,
   // use aProgress.DOMWindow to obtain the tab/window which triggered the change.
  },

}

function getURL()
{
	var locations = document.getElementById("current_url");
	locations.value = mainWindow.content.document.location.href;	

}

function getLinks()
{
	var allLinks = mainWindow.content.document.links;
	var found_links = document.getElementById("found_urls");
	found_links.value = "Found "+allLinks.length+" links";
}

function startup() {
  // Sidebar is loading
  mainWindow.getBrowser().addProgressListener(myListener);
	var display_status = document.getElementById("status");
	display_status.value = "Welcome to Siloseer";	  
	 //setXPathText1("varun"); 
}

// function pop_on_up() {
			// //setXPathText1("varun123");
			// alert('test');
// }

// function popup_init() {
               // if (document.getElementById("contentAreaContextMenu"))
                    // {
                         // document.getElementById("contentAreaContextMenu").addEventListener("command", calc_xpath, false);
						 // //alert('test_popup_init');
                    // }
// }

function shutdown() {
  // Sidebar is unloading
}

function clearLinks()
{
var cell = document.getElementById("urlList");

if ( cell.hasChildNodes() )
{
    while ( cell.childNodes.length >= 1 )
    {
        cell.removeChild( cell.firstChild );       
    } 
}

}

function restartCrawl()
{
	start=1;
	urlq=[];
	urlhash=[];
	visited=0;
	clearLinks();
	
	var crawl_depth_val = document.getElementById("crawl_depth");
	max_visited = crawl_depth_val.value;
	
	var display_status = document.getElementById("status");
	display_status.value = "SiloSeer is running";	
	
	var start_able = document.getElementById("start_button");
	start_able.disabled = true;
	
	var depth_scale = document.getElementById("crawl_depth");
	depth_scale.disabled = true;
		
	mainWindow.content.wrappedJSObject.location=mainWindow.content.document.location.href;

}


function stopCrawl()
{
	start=0;
	
	var display_status = document.getElementById("status");
	display_status.value = "Crawl has stopped";	
	
	var start_able = document.getElementById("start_button");
	start_able.disabled = false;	
	
	var depth_scale = document.getElementById("crawl_depth");
	depth_scale.disabled = false;	
}

window.addEventListener("load", startup, false);
//window.addEventListener("load", popup_init, false);

//window.addEventListener("unload", shutdown, false);

function addUrl()
{
	var currentUrl = mainWindow.content.document.location.href;	
	var objRegExp = /(.*)[\?\#].*/;
	var cleanUrl = currentUrl.replace(objRegExp, "$1");
	
	if(!(cleanUrl in urlhash))
	{
		urlhash[cleanUrl]=0;
		urlq.push(cleanUrl);
	}		
	
			
	//mainWindow.window.alert(cleanUrl);
}
	

function startCrawl()
{
	if(urlq.length < 1) return;
	if(visited>=max_visited)
	{
		var display_status = document.getElementById("status");
		display_status.value = "Finished Crawling";	
		start=0;
		return;
	}
	
	var currentUrl = urlq.shift();
	urlhash[currentUrl]=1;

	//To display extracted titles. Temporarily commented out
	
		// var links1 = document.getElementById("urlList");
		// var newItem = document.createElement("treeitem");
		// var newRow = document.createElement("treerow");
		// newItem.appendChild(newRow);

        // var foundlink = document.createElement("treecell");
		// foundlink.setAttribute("label",mainWindow.content.document.title);
		// newRow.appendChild(foundlink);

		// links1.appendChild(newItem);
		
	visited++;
	var display_visited_urls = document.getElementById("visited_urls");
	display_visited_urls.value = "Visted: "+visited;		
	
	//mainWindow.window.alert("popped url is " + currentUrl);
	
	var allLinks = mainWindow.content.document.links;

	for (var i=0; i<allLinks.length; i++) {
		var myUrl = allLinks[i].href;
		//mainWindow.window.alert("Found " + myUrl);
		var objRegExp = /(.*)[\?\#].*/;
		var cleanFoundUrl = myUrl.replace(objRegExp, "$1");		
		//mainWindow.window.alert("AFter clearning " + cleanFoundUrl);		
		if(!(cleanFoundUrl in urlhash))
		{
			if(cleanFoundUrl.search(/http/)!=-1)
			{
				urlhash[cleanFoundUrl]=0;
				urlq.push(cleanFoundUrl);
				//mainWindow.window.alert("Adding to q and hash " + cleanFoundUrl);
			}
		}

	}
	
  
	var display_urlsinq = document.getElementById("urlsinq");
	display_urlsinq.value = "Urls in Q: "+urlq.length;	
	
	var nexturl = urlq.shift();
	
	var display_next_url = document.getElementById("next_url");
	display_next_url.value = nexturl;		
	
	mainWindow.content.wrappedJSObject.location=nexturl;
}

